
from models import Song, ActiveUser, UserStat

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.api import channel


import cgi
import os

def get_song_key(lang):
    if lang=='E':
        parent='EnglishSong'
    else:
        parent='HindiSong'
    return db.Key.from_path(parent, lang)

class Main(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type']='text/plain'

        user=users.get_current_user()
        limit=30

        if user:
            user_stat=UserStat.all()
            user_stat.filter('user =', user)
            fuser=user_stat.get()
            if not fuser:
                UserStat().put()
            else:
                fuser.timesloggedin+=1
                fuser.put()

            q=ActiveUser.all()
            q.filter=('user =', user)
            u=q.get()
            if not u:
                ActiveUser().put()

            es=Song.all()
            es.ancestor(get_song_key('E'))
            english_songs=es.fetch(limit)
            
            hs=Song.all()
            hs.ancestor(get_song_key('H'))
            hindi_songs=hs.fetch(30)
            
            self.response.headers['Content-Type']='text/html'
            channel_token=channel.create_channel(user.user_id())
            template_values={'username':user.nickname(),
                             'channel_token':channel_token,
                             'hindi_songs':hindi_songs,
                             'english_songs':english_songs}
            self.response.out.write(template.render('iface.html', template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))

def main():

#    use_library('django', '1.0')
    app = webapp.WSGIApplication([('/', Main)], debug=True)
    run_wsgi_app(app)



if __name__=='__main__':
    main()
